package org.jeecg.modules.api.wlhy.digitalsignet;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.DictUtil;
import org.jeecg.modules.third.digitalseal.service.DigitalSignetService;
import org.jeecg.modules.third.digitalseal.utils.GeneratePDF;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description: APP电子签章
 * @author: luruirui
 * @date: 2021年04月20日 9:03
 */
@Api(tags="APP电子签章")
@RestController
@RequestMapping("/api/wlhy/digitalsignet")
@Slf4j
public class ApiDigitalSignetController {
    @Autowired
    private DigitalSignetService digitalSignetService;
    @Autowired
    private IHyDriverService hyDriverService;
    @Autowired
    private IHyOrderService hyOrderService;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private DictUtil dictUtil;

    @Autowired
    private GeneratePDF generatePDF;

    //获取司机实体
    private HyDriver getDriverByReq(HttpServletRequest req){
        //拿到user数据
        LoginUser loginUser = UserUtil.getLoginUser();
        String userId = loginUser.getId();
        //拿到司机数据
        QueryWrapper<HyDriver> driverWrapper = QueryGenerator.initQueryWrapper(new HyDriver(), req.getParameterMap());
        driverWrapper.eq("user_id", userId);
        HyDriver driver = hyDriverService.getOne(driverWrapper);
        return driver;
    }



    /**
     * 起草车辆挂靠声明
     */
    @AutoLog(value = "APP电子签章-起草车辆挂靠声明")
    @ApiOperation(value="APP电子签章-起草车辆挂靠声明", notes="APP电子签章-起草车辆挂靠声明")
    @PostMapping(value = "/draftVehicleHang")
    public Result<?> draftVehicleHang(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        //拿到司机数据
        HyDriver driver = getDriverByReq(req);
        if(driver == null){
            return Result.error("司机信息不存在!");
        }

        //车牌号
        String vehicleNumber = jsonObject.getString("vehicleNumber");
        //运输公司
        String companyName = jsonObject.getString("companyName");

        //如果是辽宁税务要求，不需要传任何参数，挂靠协议只和司机有关
        if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
            //...
        } else {
            if(vehicleNumber == null || StringUtils.isEmpty(vehicleNumber)){
                return Result.error("请检查车牌号是否填写！");
            }
            if(companyName == null || StringUtils.isEmpty(companyName)){
                return Result.error("请检查车辆所有人是否填写！");
            }
        }

        String contractPath = digitalSignetService.draftVehicleContract(driver, vehicleNumber, companyName);
        if(contractPath == null){
            return Result.error("未获取到合同地址");
        }
        if(contractPath.equals("")){
            return Result.error("未获取到正确的合同模板地址！");
        }
        return Result.OK(contractPath);
    }


    /**
     * 起草税务授权协议
     */
    @AutoLog(value = "APP电子签章-税务授权协议")
    @ApiOperation(value="APP电子签章-税务授权协议", notes="APP电子签章-起草税务授权协议")
    @PostMapping(value = "/draftTaxHang")
    public Result<?> draftTaxHang(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        //拿到司机数据
       /* HyDriver driver = getDriverByReq(req);
        if(driver == null){
            return Result.error("司机信息不存在!");
        }*/
        /*String contractPath = digitalSignetService.draftTaxContract(driver);
        if(contractPath == null){
            return Result.error("未获取到合同地址");
        }
        if(contractPath.equals("")){
            return Result.error("未获取到正确的合同模板地址！");
        }*/

        return Result.OK();
//        return generatePDF.addSignetForTax(driver);
    }

    /**
     * 起草司机运输合同
     */
    @AutoLog(value = "APP电子签章-起草司机运输合同")
    @ApiOperation(value="APP电子签章-起草司机运输合同", notes="APP电子签章-起草司机运输合同")
    @PostMapping(value = "/draftShipping")
    public Result<?> draftShipping(@RequestBody JSONObject jsonObject) {
        String orderId = jsonObject.getString("orderId");
        HyOrder order = hyOrderService.getById(orderId);
        if(order == null){
            return Result.error("查询不到货源信息！" + orderId);
        }
        JSONObject joOrder = dictUtil.parseObjectDict(order);
        if(joOrder == null){
            return Result.error("货源信息解析为JSONObject发生错误！");
        }
        log.info("开始起草电子运输合同, {}", jsonObject);
        String contractPath = digitalSignetService.draftShippingContract(joOrder);

//        Result result = generatePDF.pdfUtil(joOrder, driver);
        if(contractPath == null){
            return Result.error("未获取到合同地址");
        }
        if(contractPath.equals("")){
            return Result.error("未获取到正确的合同模板地址！");
        }
        return Result.OK(contractPath);
    }

    @AutoLog(value = "APP司机查看运输合同")
    @GetMapping(value = "/checkShippingContract")
    public Result<?> checkShippingContract() {
        return Result.OK(this.digitalSignetService.checkShippingContract());
    }


    /**
     * 车辆挂靠声明添加司机签章
     */
    @AutoLog(value = "APP电子签章-车辆挂靠声明添加司机签章")
    @ApiOperation(value="APP电子签章-车辆挂靠声明添加司机签章", notes="APP电子签章-车辆挂靠声明添加司机签章")
    @PostMapping(value = "/addSignetForVehicle")
    public Result<?> addSignetForVehicle(@RequestBody JSONObject jsonObject){
        String filePath = jsonObject.getString("filePath");
        String signetPath = jsonObject.getString("signetPath");
        if(filePath == null || StringUtils.isEmpty(filePath)){
            return Result.error("合同地址错误！");
        }
        if(signetPath == null || StringUtils.isEmpty(signetPath)){
            return Result.error("签名图片地址错误！");
        }

        //如果开启了辽宁税务开关，要先签属增值税专用发票协议
        if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
            LoginUser loginUser = UserUtil.getLoginUser();
            if (null == loginUser) {
                return Result.error("未获取到用户登录信息！");
            }

            HyDriver hyDriver = this.hyDriverService.getHyDriverByUserId(loginUser.getId());
            if (null == hyDriver) {
                return Result.error("未获取到司机信息！");
            }

            try {
                Result addSignetForTax = digitalSignetService.addSignetForLiaoningTax(hyDriver, signetPath);
                if (addSignetForTax.isSuccess()) {
                    hyDriver.setSwAgreement(addSignetForTax.getResult().toString());
                } else {
                    log.error("签属税务协议失败！{}", hyDriver.getDriverName());
                    return Result.error(hyDriver.getDriverName() + "签属税务协议失败");
                }
                log.info("签属增值税专用发票协议成功，{}", JSONUtil.toJsonStr(addSignetForTax));

                Result addSignetForVehicle = generatePDF.driverAffiliationForZhonghui(hyDriver, signetPath);
                if (addSignetForVehicle.isSuccess()) {
                    hyDriver.setAffiliationAgreement(addSignetForVehicle.getResult().toString());
                } else {
                    log.error("签属业务挂靠协议失败！{}", hyDriver.getDriverName());
                    return Result.error(hyDriver.getDriverName() + "签属业务挂靠协议失败");
                }
                log.info("签属业务挂靠协议成功，{}", JSONUtil.toJsonStr(addSignetForVehicle));

                hyDriver.setDriverAutograph(signetPath);
                this.hyDriverService.updateById(hyDriver);

                return addSignetForVehicle;
            } catch (Exception e) {
                log.error("签属税务协议失败，{}", e.getMessage());
                return Result.error("签属税务协议失败！");
            }
        } else {
            return digitalSignetService.addSignetForVehicle(filePath, signetPath);
        }
    }

    /**
     * 运输合同添加司机签章
     */
    @AutoLog(value = "APP电子签章-运输合同添加司机签章")
    @ApiOperation(value="APP电子签章-运输合同添加司机签章", notes="APP电子签章-运输合同添加司机签章")
    @PostMapping(value = "/addSignetForShipping")
    public Result<?> addSignetForShipping(@RequestBody JSONObject jsonObject, HttpServletRequest req){
//        String filePath = jsonObject.getString("filePath");
        String signetPath = jsonObject.getString("signetPath");
        //移动端添加新的传参修改pdf合同模板
        String id = jsonObject.getString("id");
        //拿到司机数据
        HyDriver driver = getDriverByReq(req);
        //保存司机签名图片
        driver.setDriverAutograph(signetPath);
        hyDriverService.updateById(driver);

        if(driver == null){
            return Result.error("司机信息不存在!");
        }


        if(signetPath == null || StringUtils.isEmpty(signetPath)){
            return Result.error("签名图片地址错误！");
        }
        HyOrder order = hyOrderService.getById(id);
        if(order == null){
            return Result.error("货源信息不存在!");
        }
        JSONObject joOrder = dictUtil.parseObjectDict(order);

        if (null != order.getSendDate()) {
            joOrder.put("sendDate", DateUtils.dateTimeToString(order.getSendDate()));
        }
        if (null != order.getReceiveDate()) {
            joOrder.put("receiveDate", DateUtils.dateTimeToString(order.getReceiveDate()));
        }

       // Result result = generatePDF.pdfUtil(joOrder,null, driver);

        return Result.OK();
    }

    /**
     * 税务授权协议添加司机签章
     */
    @AutoLog(value = "APP电子签章-税务授权协议")
    @ApiOperation(value="APP电子签章-税务授权协议", notes="APP电子签章-税务授权协议")
    @PostMapping(value = "/addSignetForTax")
    public Result<?> addSignetForTax(@RequestBody JSONObject jsonObject,HttpServletRequest req) throws IOException {
        String signetPath = jsonObject.getString("signetPath");
        String orderId = jsonObject.getString("orderId");
        if(signetPath == null || StringUtils.isEmpty(signetPath)){
            return Result.error("签名图片地址错误！");
        }if(orderId == null || StringUtils.isEmpty(orderId)){
            return Result.error("货源参数错误！");
        }
        HyDriver driver = getDriverByReq(req);
        Result addSignetForTax = generatePDF.addSignetForTax(orderId,driver, signetPath);
        if(addSignetForTax.isSuccess()){
            driver.setSwAgreement(addSignetForTax.getResult().toString());
            hyDriverService.updateById(driver);
        }
        return addSignetForTax;
    }

    /**
     * 税务授权协议添加司机签章
     */
    @AutoLog(value = "APP电子签章-司机签署挂靠协议")
    @ApiOperation(value="APP电子签章-司机签署挂靠协议", notes="APP电子签章-司机签署挂靠协议")
    @PostMapping(value = "/driverSignAndRegister")
    public Result<?> driverSignAndRegister(@RequestBody JSONObject jsonObject,HttpServletRequest req) throws IOException {
        String signetPath = jsonObject.getString("signetPath");
        String orderId = jsonObject.getString("orderId");
        if(signetPath == null || StringUtils.isEmpty(signetPath)){
            return Result.error("签名图片地址错误！");
        }if(orderId == null || StringUtils.isEmpty(orderId)){
            return Result.error("货源参数错误！");
        }
        HyDriver driver = getDriverByReq(req);
        Result driverSignAndRegister = generatePDF.driverAffiliationForZhonghui(driver, signetPath);

        if(driverSignAndRegister.isSuccess()){
            driver.setAffiliationAgreement(driverSignAndRegister.getResult().toString());
            hyDriverService.updateById(driver);
        }
        return driverSignAndRegister;
    }

    /**
     * 司机签署代开协议
     */
    @AutoLog(value = "APP电子签章-司机签署代开协议")
    @ApiOperation(value="APP电子签章-司机签署代开协议", notes="APP电子签章-司机签署代开协议")
    @PostMapping(value = "/kaiyundaikai")
    public Result<?> kaiyundaikai(@RequestBody JSONObject jsonObject,HttpServletRequest req) throws IOException {
        String signetPath = jsonObject.getString("signetPath");
        String orderId = jsonObject.getString("orderId");
        if(signetPath == null || StringUtils.isEmpty(signetPath)){
            return Result.error("签名图片地址错误！");
        }if(orderId == null || StringUtils.isEmpty(orderId)){
            return Result.error("货源参数错误！");
        }
        HyDriver driver = getDriverByReq(req);
        Result driverSignAndRegister = generatePDF.kaiyundaikai(orderId, driver, signetPath);

        if(driverSignAndRegister.isSuccess()){
            driver.setSwAgreement(driverSignAndRegister.getResult().toString());
            hyDriverService.updateById(driver);
        }
        return driverSignAndRegister;
    }



}
